package club.beimeng.demos.demo2021年5月18日;

import java.util.Scanner;
import java.util.Queue;
import java.util.LinkedList;

public class Two{
    static int N = 100010;
    static int[] h = new int[N];
    static int[] e = new int[N];
    static int[] ne = new int[N];
    static int[] d = new int[N];                //储存每个节点距离起点的距离
    static Queue<Integer> q = new LinkedList<>();
    static boolean[] st = new boolean[N];
    static int idx,n;

    public static void main(String[] args){
        Scanner in = new Scanner(System.in);

        n = in.nextInt();
        int m = in.nextInt();

        for(int i = 0; i < N; i ++)
        {
            h[i] = -1;
            d[i] = -1;
        }

        for(int i = 0; i < m; i ++)
        {
            int a = in.nextInt();
            int b = in.nextInt();
            add(a,b);
        }

        System.out.print(bfs(1));           //求的是1-n的最短距离，从1开始搜就可以了
    }

    private static void add(int a, int b)
    {
        e[idx] = b;
        ne[idx] = h[a];
        h[a] = idx++;
    }

    private static int bfs(int u)
    {
        q.offer(u);
        d[1] = 0;                        //自己距离自己为0，在这里的作用相当于表示走过了

        while(q.size() != 0)
        {
            int t = q.poll();
            for(int i = h[t]; i != -1; i = ne[i])
            {
                int j = e[i];           //j相当于当前节点的子节点,因为当前节点会不满足条件直接跳出循环
                if(d[j] == -1)
                {
                    q.offer(j);
                    d[j] = d[t] + 1;
                }
            }
        }
        return d[n];
    }
}

/*
 *
 * @author Mr.Bao
 * @date
 */